<template>
  <view class="page-index-format">
    <Toast ref="ToastRef" />
    <Loader ref="LoaderRef" />
    <QrPopup ref="QrPopupRef" />
    <OrderPopup ref="OrderPopupRef" @ok="handleRuleInfo" />
    <Header text="点单"> </Header>
    <view class="container">
      <view class="scroll-view" v-if="store.state.menuList.length > 0">
        <scroll-view
          class="scroll-menu-category"
          scroll-y
          scroll-with-animation
          scroll-animation-duration="200"
          :show-scrollbar="false"
        >
          <view class="scroll-content">
            <view class="list">
              <view
                v-for="(item, index) in store.state.menuList"
                :key="index"
                :class="['item', index === selectIndex ? 'active' : '']"
                @click="handleGotoFoots(index)"
              >
                <view class="text">{{ item.name }}</view>
              </view>
            </view>
          </view>
        </scroll-view>
        <scroll-view
          class="scroll-menu-foots"
          scroll-y
          scroll-with-animation
          scroll-animation-duration="200"
          :show-scrollbar="false"
          :scroll-into-view="scrollIntoViewFoots"
          @scroll="handleScrollFoots"
        >
          <view class="scroll-content">
            <view
              :id="'home_foot_' + index1"
              class="list home_foot_list"
              v-for="(item1, index1) in store.state.menuList"
              :key="index1"
            >
              <view class="head">{{ item1.name }}</view>
              <view class="items">
                <view class="item" v-for="item2 in item1.goodsList" :key="item2.id">
                  <view
                    class="bg"
                    :style="'background-image:url(' + item2.imgUrl + ')'"
                  ></view>
                  <view class="info">
                    <view class="name">{{ item2.name }}</view>
                    <view class="bottom">
                      <view class="price">
                        {{ item2.sellPrice }}{{ item2.tagList.length > 0 ? "起" : "" }}
                      </view>
                      <view
                        class="btn-rule"
                        v-if="item2.tagList.length > 0"
                        @click="handleRule(item2)"
                      >
                        <view class="buyNum" v-if="item2.__buyInfo.length > 0">
                          {{ countRuleNum(item2.__buyInfo) }}
                        </view>
                        <view>选规格</view>
                      </view>
                      <view class="btn-num" v-else>
                        <view
                          class="minus"
                          v-show="item2.__buyInfo.length > 0"
                          @click="handleBuyNum('-', item2)"
                        ></view>
                        <view class="text" v-show="item2.__buyInfo.length > 0">
                          {{ item2.__buyInfo.length }}
                        </view>
                        <view class="add" @click="handleBuyNum('+', item2)"></view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="cartList" v-if="isCartList">
          <view class="bg" @click="isCartList = false"></view>
          <view class="content">
            <view class="title">购物车</view>
            <view class="list">
              <view class="item1" v-for="(item1, index1) in orderList.list" :key="index1">
                <template v-if="item1.tagList.length > 0">
                  <view
                    class="item2"
                    v-for="(item2, index2) in item1.__buyInfo"
                    :key="index2"
                  >
                    <view
                      class="bg"
                      :style="'background-image:url(' + item1.imgUrl + ')'"
                    ></view>
                    <view class="info">
                      <view class="name">
                        <view class="text1">{{ item1.name }}</view>
                        <view class="text2">{{ item2.tagsStr }}</view>
                      </view>
                      <view class="price">
                        ￥{{ (item1.sellPrice + item2.tagsCountPrice) * item2.num }}
                      </view>
                      <view class="btn-num">
                        <view
                          class="minus"
                          @click="handleRuleBuyNum('-', item1, item2)"
                        ></view>
                        <view class="text">{{ item2.num }}</view>
                        <view
                          class="add"
                          @click="handleRuleBuyNum('+', item1, item2)"
                        ></view>
                      </view>
                    </view>
                  </view>
                </template>
                <view v-else class="item2">
                  <view
                    class="bg"
                    :style="'background-image:url(' + item1.imgUrl + ')'"
                  ></view>
                  <view class="info">
                    <view class="name"
                      ><view class="text1">{{ item1.name }}</view></view
                    >
                    <view class="price">
                      ￥{{ item1.sellPrice * item1.__buyInfo.length }}
                    </view>
                    <view class="btn-num">
                      <view class="minus" @click="handleBuyNum('-', item1)"></view>
                      <view class="text"> {{ item1.__buyInfo.length }}</view>
                      <view class="add" @click="handleBuyNum('+', item1)"></view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="cartOrder" v-show="orderList.num > 0">
          <view class="format">
            <view class="icon" @click.stop="isCartList = !isCartList">
              <view class="num">{{ orderList.num }}</view>
            </view>
            <view class="price">
              <view
                :class="[
                  'format',
                  store.isMember.value && store.state.walletAmount > 0 ? 'favorable' : '',
                ]"
              >
                <view
                  class="text1"
                  v-if="store.isMember.value && store.state.walletAmount > 0"
                >
                  ￥{{
                    orderList.price - store.state.walletAmount > 0
                      ? utils.mathRound2(orderList.price - store.state.walletAmount)
                      : 0
                  }}
                </view>
                <view class="text2"> ￥{{ orderList.price }} </view>
              </view>
            </view>
            <view class="btn" @click="handleOrder">下单</view>
          </view>
        </view>
      </view>
      <view class="empty-view" v-else>
        <view class="empty-content">
          <view class="bg"></view>
          <view class="text">没有相关菜品</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, defineExpose, getCurrentInstance, computed, defineEmits } from "vue";
import apiGoods from "@/api/goods";
import apiOrder from "@/api/order";
import store from "@/store/index";
import utils from "@/utils/utils";
const appInstance = getCurrentInstance().proxy;

const emit = defineEmits(["tab"]);
const OrderPopupRef = ref();
const QrPopupRef = ref();
const LoaderRef = ref();
const ToastRef = ref();
const selectIndex = ref(0);
const scrollIntoViewFoots = ref();
const isCartList = ref(false);
const orderList = computed(() => {
  let list = [];
  let num = 0;
  let price = 0;
  let order = [];
  for (let t1 in store.state.menuList) {
    let myMenu = store.state.menuList[t1];
    for (let t2 in myMenu.goodsList) {
      let myGoods = myMenu.goodsList[t2];
      if (myGoods.__buyInfo.length > 0) {
        list.push(myGoods);
        for (let b in myGoods.__buyInfo) {
          let buyNum = myGoods.__buyInfo[b].num;
          let buyPrice = myGoods.sellPrice;
          let tagList = [];
          let tagItemLists = [];
          for (let l1 in myGoods.tagList) {
            for (let l2 in myGoods.tagList[l1].tagItemList) {
              tagList.push(myGoods.tagList[l1].tagItemList[l2]);
            }
          }
          for (let n in tagList) {
            if (myGoods.__buyInfo[b].tags.indexOf(tagList[n].id) > -1) {
              buyPrice = buyPrice + tagList[n].sellPrice;
              tagItemLists.push(tagList[n].id);
            }
          }
          for (let m = 0; m < buyNum; m++) {
            order.push({ id: myGoods.id, tagItemList: tagItemLists });
          }
          num = num + buyNum;
          price = price + buyPrice * buyNum;
        }
      }
    }
  }
  console.log(list);
  if (num === 0) {
    isCartList.value = false;
  }
  return {
    list,
    num,
    order,
    price: Math.round(price * 100) / 100,
  };
});

const handleRule = (item) => {
  OrderPopupRef.value.show(item);
};

const countRuleNum = (arr) => {
  let num = 0;
  arr.forEach((item) => {
    num += item.num;
  });
  return num;
};

const handleRuleInfo = (item, opts) => {
  item.__buyInfo.push(opts);
  OrderPopupRef.value.close();
};

const handleGotoFoots = (index) => {
  selectIndex.value = index;
  scrollIntoViewFoots.value = "home_foot_" + index;
};

const handleScrollFoots = (e) => {
  const query = uni.createSelectorQuery().in(appInstance);
  query
    .selectAll(".home_foot_list")
    .boundingClientRect((data) => {
      let height = 0;
      for (var cate = 0; cate < data.length; cate++) {
        if (
          e.detail.scrollTop > height &&
          e.detail.scrollTop < height + data[cate].height
        ) {
          selectIndex.value = cate;
          break;
        } else {
          height += data[cate].height;
        }
      }
    })
    .exec();
};

const handleRuleBuyNum = (type, item1, item2) => {
  switch (type) {
    case "+":
      item2.num++;
      break;
    case "-":
      item2.num--;
      if (item2.num === 0) {
        for (let i = 0; i < item1.__buyInfo.length; i++) {
          if (item1.__buyInfo[i] === item2) {
            item1.__buyInfo.splice(i, 1);
            break;
          }
        }
      }
      break;
  }
};

const handleBuyNum = (type, item) => {
  switch (type) {
    case "+":
      item.__buyInfo.push({ num: 1, tags: [], tagsStr: 0, tagsCountPrice: 0 });
      break;
    case "-":
      item.__buyInfo.shift();
      break;
  }
};
const getGoodsList = async () => {
  store.state.menuList = [];
  if (store.isOrderType.value) {
    let params = Object.assign({ orderType: store.state.orderType }, store.state.qr);
    console.log(params);
    let data = await apiGoods.list(params);
    for (let t1 in data) {
      let my1 = data[t1].goodsList;
      for (let t2 in my1) {
        my1[t2]["__buyInfo"] = [];
      }
    }
    store.state.menuList = data;
  }
};

const payResult = async (type, data) => {
  switch (type) {
    case "success":
      ToastRef.value.show({
        title: "恭喜",
        content: "支付成功",
        onClose: async () => {
          try {
            store.isMember.value && (await store.updateWalletAmount());
          } catch (err) {}
          QrPopupRef.value.show({ title: data.mealCode, data: data.mealQrCode });
        },
      });
      break;
    case "fail":
      ToastRef.value.show({
        title: "抱歉",
        content: "支付失败",
        onClose: async () => {
          try {
            LoaderRef.value.show("订单状态更新中");
            await apiOrder.cancelPay({ id: data.id });
            store.isMember.value && (await store.updateWalletAmount());
          } catch (err) {}
          LoaderRef.value.hide(() => {
            emit("tab", "ORDER");
          });
        },
      });
      break;
  }
};
const handleOrder = async () => {
  try {
    LoaderRef.value.show("支付中");
    let walletAmount = 0;
    let payAmount = orderList.value.price;
    if (store.isMember.value) {
      await store.updateWalletAmount();
      if (store.state.walletAmount - orderList.value.price >= 0) {
        payAmount = 0;
        walletAmount = orderList.value.price;
      } else {
        payAmount = orderList.value.price - store.state.walletAmount;
        walletAmount = store.state.walletAmount;
      }
    }
    let params = Object.assign(
      {
        orderType: store.state.orderType,
        payMethod: store.state.payMethod,
        goodsList: orderList.value.order,
        walletAmount,
        payAmount: Math.round(payAmount * 100) / 100,
      },
      store.state.qr
    );
    if (store.state.orderType === 31) {
      params["expectAt"] = store.state.expectAt;
    }
    console.log(params);
    let data = await apiOrder.pay(params);
    getGoodsList();
    if (data.payStatus === 11) {
      LoaderRef.value.hide(() => {
        payResult("success", data);
      });
    } else {
      uni.requestPayment({
        nonceStr: data.extraMap.nonceStr,
        package: data.extraMap.package,
        paySign: data.extraMap.paySign,
        timeStamp: data.extraMap.timeStamp,
        signType: data.extraMap.signType,
        success: () => {
          LoaderRef.value.hide(() => {
            payResult("success", data);
          });
        },
        fail: () => {
          LoaderRef.value.hide(() => {
            payResult("fail", data);
          });
        },
      });
    }
  } catch (err) {
    LoaderRef.value.hide(() => {
      ToastRef.value.show({ title: "抱歉", content: err });
    });
  }
};

defineExpose({
  __onPageMounted: async () => {},
  __onPageLoad: (opts) => {},
  __onPageShow: () => {},
  __onPageLeave: () => {},
  __onPageEnter: () => {
    getGoodsList();
  },
});
</script>
<style scoped lang="scss">
.page-index-format {
  position: relative;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  & > .container {
    position: relative;
    flex: 1;
    overflow: hidden;
    height: 100%;
    background: #f1f8fa;
    display: flex;
    box-sizing: border-box;
    border-top: solid 4rpx #f3f3f3;
    & > .scroll-view {
      position: relative;
      display: flex;
      height: 100%;
      width: 100%;
      & > .cartList {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1000;
        & > .bg {
          position: absolute;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.4);
        }
        & > .content {
          position: absolute;
          bottom: 0;
          left: 0;
          max-height: 60%;
          width: 100%;
          padding-bottom: 100rpx;
          background: #fff;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          & > .title {
            color: #333;
            font-weight: bold;
            font-size: 32rpx;
            padding: 20rpx;
            border-bottom: solid 2rpx #eee;
            box-sizing: border-box;
          }
          & > .list {
            width: 100%;
            padding: 30rpx 20rpx;
            box-sizing: border-box;
            flex: 1;
            height: 0;
            overflow: auto;
            & > .item1 {
              position: relative;
              .item2 {
                position: relative;
                display: flex;
                padding: 30rpx 0;
                border-bottom: solid 2rpx #eee;
                box-sizing: border-box;
                & > .bg {
                  position: relative;
                  height: 120rpx;
                  width: 120rpx;
                  background-size: cover;
                  background-repeat: no-repeat;
                  background-position: center center;
                  margin-right: 30rpx;
                }
                & > .info {
                  width: 0;
                  flex: 1;
                  display: flex;
                  justify-content: space-between;
                  & > .name {
                    flex: 1;
                    width: 0;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    .text1 {
                      font-size: 32rpx;
                      color: #333;
                    }
                    .text2 {
                      font-size: 24rpx;
                      color: #5d656d;
                      padding-top: 10rpx;
                    }
                  }
                  & > .price {
                    font-size: 28rpx;
                    color: #666;
                    width: 120rp;
                    padding: 0 20rpx;
                  }
                  & > .btn-num {
                    color: #333;
                    font-size: 30rpx;
                    display: flex;
                    align-items: center;
                    & > .minus {
                      background-image: var(--Img_Common_Minus);
                    }
                    & > .add {
                      background-image: var(--Img_Common_Add);
                    }
                    & > .minus,
                    & > .add {
                      position: relative;
                      height: 40rpx;
                      width: 40rpx;
                      background-size: cover;
                      background-repeat: no-repeat;
                      background-position: center center;
                    }
                    & > .text {
                      line-height: 1;
                      padding: 0 30rpx;
                    }
                  }
                }
              }
            }
          }
        }
      }
      & > .cartOrder {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 100rpx;
        z-index: 1000;
        & > .format {
          width: 100%;
          height: 100%;
          background: #f0f0f1;
          display: flex;
          padding-left: 20rpx;
          font-size: 38rpx;
          align-items: center;
          box-sizing: border-box;
          & > .icon {
            position: relative;
            height: 70rpx;
            width: 70rpx;
            background-image: var(--Img_Common_Shop);
            background-size: 50% 50%;
            background-color: #4d4d4d;
            background-position: center center;
            background-repeat: no-repeat;
            border-radius: 50%;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            & > .num {
              position: absolute;
              right: 0;
              top: 0;
              font-size: 20rpx;
              color: #fff;
              background: #e73b29;
              border-radius: 50%;
              width: 40rpx;
              height: 40rpx;
              justify-content: center;
              display: flex;
              align-items: center;
              transform: translate(40%, -30%);
            }
          }
          & > .price {
            flex: 1;
            height: 100%;
            width: 0;
            padding: 20rpx 20rpx 20rpx 35rpx;
            box-sizing: border-box;
            & > .format {
              position: relative;
              font-weight: bold;
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: center;
              &.favorable .text2 {
                font-size: 26rpx;
                color: #333;
                text-decoration: line-through;
              }
              .text1,
              .text2 {
                font-size: 30rpx;
                color: #e73b29;
              }
            }
          }
          & > .btn {
            height: 100%;
            color: #fff;
            background-color: var(--Main_Color);
            padding: 0 60rpx;
            display: flex;
            align-items: center;
          }
        }
      }
      & > .scroll-menu-category,
      & > .scroll-menu-foots {
        .scroll-content {
          position: relative;
          width: 100%;
        }
      }
      & > .scroll-menu-category {
        width: 150rpx;
        height: 100%;
        background: #f8f8f8;
        .scroll-content > .list {
          .item {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #a3a4a5;
            font-size: 28rpx;
            padding: 30rpx 5rpx;
            border-left: solid 6rpx transparent;
            &.active {
              color: #333;
              background: #ffffff;
              border-color: var(--Main_Color);
            }
          }
        }
      }
      & > .scroll-menu-foots {
        flex: 1;
        height: 100%;
        width: 0;
        background: #fff;
        .scroll-content {
          padding: 0 30rpx 50rpx 30rpx;
          box-sizing: border-box;
          & > .list {
            position: relative;
            width: 100%;
            padding: 30rpx 0;
            box-sizing: border-box;
            & > .head {
              position: relative;
              font-size: 32rpx;
              padding-bottom: 30rpx;
              color: #333;
              font-weight: bold;
            }
            & > .items {
              position: relative;
              width: 100%;
              & > .item {
                position: relativ e;
                display: flex;
                padding-bottom: 60rpx;
                &:last-child {
                  padding-bottom: 0;
                }
                & > .bg {
                  position: relative;
                  height: 120rpx;
                  width: 120rpx;
                  background-size: cover;
                  background-repeat: no-repeat;
                  background-position: center center;
                  margin-right: 30rpx;
                }
                & > .info {
                  width: 0;
                  flex: 1;
                  display: flex;
                  flex-direction: column;
                  justify-content: space-between;
                  & > .name {
                    font-size: 28rpx;
                    color: #666;
                  }
                  & > .bottom {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-size: 28rpx;
                    color: #333;
                    & > .price {
                      flex: 1;
                      width: 0;
                    }
                    & > .btn-rule {
                      position: relative;
                      background: var(--Main_Color);
                      padding: 15rpx 30rpx;
                      border-radius: 100rpx;
                      color: #fff;
                      font-size: 24rpx;
                      .buyNum {
                        position: absolute;
                        right: 0;
                        top: 0;
                        font-size: 20rpx;
                        color: #fff;
                        background: #e73b29;
                        border-radius: 50%;
                        width: 40rpx;
                        height: 40rpx;
                        justify-content: center;
                        display: flex;
                        align-items: center;
                        transform: translate(40%, -40%);
                      }
                    }
                    & > .btn-num {
                      font-size: 24rpx;
                      display: flex;
                      align-items: center;
                      & > .minus {
                        background-image: var(--Img_Common_Minus);
                      }
                      & > .add {
                        background-image: var(--Img_Common_Add);
                      }
                      & > .minus,
                      & > .add {
                        position: relative;
                        height: 40rpx;
                        width: 40rpx;
                        background-size: cover;
                        background-repeat: no-repeat;
                        background-position: center center;
                      }
                      & > .text {
                        line-height: 1;
                        padding: 0 30rpx;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    & > .empty-view {
      position: relative;
      width: 100%;
      height: 100%;
      display: flex;
      justify-items: center;
      align-items: center;
      & > .empty-content {
        position: relative;
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-items: center;
        align-items: center;
      }
      .bg {
        background-image: var(--Img_Order_Gif);
        background-size: auto 100%;
        background-position: center center;
        background-repeat: no-repeat;
        height: 300rpx;
        width: 200rpx;
        margin-bottom: 40rpx;
      }
      .text {
        position: relative;
        font-size: 28rpx;
        color: #8a8a8b;
        line-height: 1;
        margin-bottom: 15rpx;
      }
    }
  }
}
</style>
